<template>
  <el-form v-bind="element.props" v-loading="requesting" class="lab-form">
    <lab-form-item :element="element" :elements="elements" :index=index :model-data="modelData" />
  </el-form>
</template>

<script>
import LabBase from "../../mixins/LabBase";
import LabRequest from "../../mixins/LabRequest";
import Util from "../../utils/Util";

export default {
  name: "LabForm",
  mixins: [ LabBase,LabRequest],
  provide() {
    return {
      parentElement: this
    }
  },
  created() {
    this.$LabRender.autoFill(this.element, this)
    const { elements } = this.element
    elements.forEach(item => {
      this.$LabRender.autoFill(item, this)
    })
    this.loadSource()
  },
  methods: {
    loadSource(localFilters){
      let sourceRequest = this.findRequest('formSource')
      if (!sourceRequest) {
        sourceRequest = this.findRequest('source')
      }
      if (!sourceRequest) {
        return
      }
      const { props } = this.element
      if (Util.isEmpty(props.rowKey)) {
        return;
      }
      const keyVal = this.modelData[props.rowKey]
      if (Util.isEmpty(keyVal)) {
        return;
      }
      this.addFilter({ field:props.rowKey, op: '=',value:keyVal })
      const bodyArgs = this.getBody(sourceRequest,this.modelData)
      if (!Util.isEmpty(localFilters)) {
        if (Util.isArray(localFilters)) {
          localFilters.forEach(item => this.addFilter(item))
        } else {
          this.addFilter(localFilters)
        }
      }
      this.dispatchRequest('source',this.modelData, bodyArgs)
          .then(res => {
            this.dataSource.splice(0, this.dataSource.length)
            if (!Util.isEmpty(res)) {
              this.dataSource = res
              if (!Util.isEmpty(this.dataSource)) {
                Util.copyAttr(this.dataSource[0],this.modelData,null,this)
              }
            } else {
              console.info('节点数据源请求:', this.element, res)
            }
            setTimeout(() => {
              this.requesting = false
            }, 100)
          })
    },
    saveData(refresh) {
      return new Promise(resolve => {
        this.saveByModel(this.modelData, refresh)
            .then(res => {
              this.$resultMsg(this, res)
              if (res.code === 200) {
                this.$Util.copyAttr(res.data[0], this.modelData, null, this)
              }
              resolve(res)
            })
      })
    }
  }
}
</script>
